package com.mr.security.web.commons.handler;

import com.mr.security.web.commons.config.SecurityPropertiesConfig;
import com.mr.security.web.commons.utils.ConstantEnum;
import com.mr.security.web.commons.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Class: CustomAuthenticationSuccessHandle
 * User (作者):MRui
 * TODO (描述)：身份验证失败处理
 * Date 2019-01-20 14:47
 */
@Slf4j
@Component
public class CustomAuthenticationFailureHandle extends SimpleUrlAuthenticationFailureHandler{

    /** 属性配置类 */
    @Autowired
    private SecurityPropertiesConfig securityProperties;

    /**
    * User (作者): MRui
    * TODO (描述)：重写登陆身份验证失败后的方法
    * Data：2019-01-20 15:26
    */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        //如果配置是返回json的形式（前后端分离）
        if (ConstantEnum.AUTHENTICATION_JSON.getMessage().equals(securityProperties.getLoginType())){
            //String  username = exception.getMessage()
            log.info("用户:{},身份验证失败！不允许登陆");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            //返回消息
            response.getWriter().write(JsonUtil.toJson(exception.getMessage()));
        }else {
            super.onAuthenticationFailure(request,response,exception);
        }
    }
}
